package com.lefevre.cms.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.util.Properties;

/**
 * yml文件工具
 *
 * @author Lefevre
 */
public class YmlUtils {
    private static final Logger logger = LoggerFactory.getLogger(YmlUtils.class);

    /**
     * 读取yml文件
     *
     * @param fileName 文件名称 例如application.yml
     * @param key      yml属性key
     */
    public static Object getYmlProperty(String fileName, Object key) {
        Resource resource = new ClassPathResource(fileName);
        Properties properties;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties = yamlFactory.getObject();
        } catch (Exception e) {
            logger.error("读取yml文件属性错误 " + fileName, e);
            return null;
        }
        return properties.get(key);
    }

    /**
     * 读取yml文件
     *
     * @param fileName 文件名称 例如application.yml
     */
    public static Properties getYml(String fileName) {
        Resource resource = new ClassPathResource(fileName);
        Properties properties;
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties = yamlFactory.getObject();
        } catch (Exception e) {
            logger.error("读取yml文件错误 " + fileName, e);
            return null;
        }
        return properties;
    }
}
